<template>
  <div class="page-container fullpage">
    <el-card>
      <h3>修改用户</h3>
      <el-form :model="form" style="margin-top:12px">
        <el-form-item label="英文名">
          <el-input v-model="form.enName" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.mobile" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker v-model="form.birthday" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">保存</el-button>
          <el-button style="margin-left:8px" @click="() => router.push('/admin/users')">返回用户管理</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '../utils/api'

const route = useRoute()
const router = useRouter()
const username = route.params.username as string || ''
const form = ref<any>({ enName: '', mobile: '', email: '', birthday: '' })

const load = async () => {
  if (!username) return
  try {
    const resp: any = await api.get('/user/search', { params: { username } })
    let user = resp && resp.operationResult === 'SUCC' ? (resp.data && resp.data[0]) || resp.data : null
    if (!user) {
      const usersResp: any = await api.get('/users')
      const list = Array.isArray(usersResp?.data) ? usersResp.data : (Array.isArray(usersResp) ? usersResp : [])
      user = list.find((u: any) => u.userName === username || u.username === username) || null
    }
    if (user) {
      form.value.enName = user.enName || ''
      form.value.mobile = user.mobile || ''
      form.value.email = user.email || ''
      form.value.birthday = user.birthday || user.birthdate || ''
    }
  } catch (err) { console.error('load edit user', err) }
}

const submit = async () => {
  try {
    const payload = { enName: form.value.enName, mobile: form.value.mobile, email: form.value.email, birthday: form.value.birthday }
    const resp: any = await api.put(`/user/${encodeURIComponent(username)}`, payload)
    if (resp && resp.operationResult === 'SUCC') {
      try { router.push('/admin/users') } catch (e) {}
    } else {
      console.warn('update failed', resp)
    }
  } catch (err) { console.error('update err', err) }
}

onMounted(() => { load() })
</script>

<style scoped>
.page-container { padding: 16px }
</style>
